#pragma once

#include <iostream>
#include <string>
#include <vector>
#include "Log.hpp"
#include "inetAddr.hpp"
#include "Mutex.hpp"

using namespace MutexMouble;
using namespace LogModule;

class Route
{
private:
    bool IsExist(InetAddr& peer)
    {
        for(auto& user:_online_user)
        {
            if(user == peer)
            {
                return true;
            }    
        }
        return false;
    }

    void AddrUser(InetAddr& peer)
    {
        LOG(LogLevel::INFO) << "新增一个在线用户:" << peer.StringAddr();
        _online_user.push_back(peer);
    }

    void DeleteUser(InetAddr& peer)
    {
        for(auto iter = _online_user.begin(); iter != _online_user.end(); iter++)
        {
            if(*iter == peer)
            {
                LOG(LogLevel::INFO) << "删除一个在线用户:" << peer.StringAddr();
                _online_user.erase(iter);
                return;
            }
        }
        
    }

public:
    Route(){}
    void MessageRoute(int sockfd, const std::string& message, InetAddr& peer)
    { 
        LockGuard  lockguard(_mutex);
        if(!IsExist(peer))
        {
            AddrUser(peer);
        }

        std::string SendMessage = peer.StringAddr() + " Say: " + message;
        for(auto &user:_online_user)
        {   
            LOG(LogLevel::DEBUG) << "send " << message << " to " << user.StringAddr(); 
            sendto(sockfd, SendMessage.c_str(), SendMessage.size(), 0, (const struct sockaddr*)&(user.NetAddr()), sizeof(user.NetAddr()));
        }

        if(message == "quit")
        {
            DeleteUser(peer);
        }

    }
    ~Route(){}
private:
    std::vector<InetAddr> _online_user; // 在线用户
    Mutex _mutex;
};